package com.woniuxy.test;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @Author: 马宇航
 * @Todo: 模拟jedis客户端,往redis服务端发送消息
 * @DateTime: 22/02/28/0028 下午 3:34
 * @Component: 成都蜗牛学苑
 **/
public class MyjedisClient {
    Socket socket;
    /**
     * 默认构造，访问6379
     * ChangeLog : 1. 创建 (22/02/28/0028 下午 3:37 [马宇航]);
     *
     * @return null
    */
    public MyjedisClient() {
        try {
            this.socket = new Socket("localhost",6379);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public MyjedisClient(String url,int port){
        try {
            this.socket = new Socket(url,port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 模拟redis的set操作字符串方法
     * ChangeLog : 1. 创建 (22/02/28/0028 下午 3:39 [马宇航]);
     * @param key
     * @param value
     * @return void
    */
    public void set(String key,String value) throws IOException {
        StringBuffer sb = new StringBuffer();
        //都是基于日志来模拟对应的数据
        sb.append("*3").append("\r\n");
        sb.append("$3").append("\r\n");
        sb.append("SET").append("\r\n");
        sb.append("$").append(key.length()).append("\r\n");
        sb.append(key).append("\r\n");
        sb.append("$").append(value.length()).append("\r\n");
        sb.append(value).append("\r\n");
        byte[] bytes = sb.toString().getBytes();
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(bytes);
        socket.close();
    }
}
